package com.genius.adminmanager.user.service.impl;

import java.io.OutputStream;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.genius.adminmanager.other.entity.ResponseJson;
import com.genius.adminmanager.user.entity.UserJson;
import com.genius.adminmanager.user.service.UserServiceAdapter;
import com.genius.workflow.config.DefaultConfiguration;
import com.genius.workflow.page.PageResult;
import com.genius.workflow.page.SearchResult;
import com.genius.workflow.page.SqlLang;
import com.genius.workflow.util.ConnectionException;
import com.genius.workflow.util.DBClosedException;
import com.genius.workflow.util.DBTools2;
import com.genius.workflow.util.ExportExcel;

@Service("userExportService")
public class UserExportServiceImpl extends UserServiceAdapter{

	@Override
	public JSONObject exportExcel(HttpServletRequest request, HttpServletResponse responseServlet,JSONObject response) {

		if(request.getParameterMap().size()==0){
    		response.put(ResponseJson.status, 1000);
    		response.put(ResponseJson.msg, "错误的请求");
    		return response;
    	}
		try {
			String selectSB = "SELECT userId,username,name,password,command,sex,phone,mail,createTime,status,(select group_concat(name)name from t_group where find_in_set(groupId,a.groupId)) groupname,jobnumber,remark FROM `t_user` a where a.userId!=?";
			String whereKey = request.getParameter(PageResult.search);
			JSONArray json = JSONArray.parseArray(whereKey);
			JSONObject search = new JSONObject();
			search.put(PageResult.search, json);
	    	String format =  request.getParameter(PageResult.format);
	    	
	    	String tableTitle =(String) request.getParameter(PageResult.exportTitle);
	    	String tableField =(String) request.getParameter(PageResult.exportField);
	    	String [] tableTitles = tableTitle.split(DefaultConfiguration.separator_douhao);
	    	String [] tableFields = tableField.split(DefaultConfiguration.separator_douhao);
	
	    	SearchResult parmObject = DBTools2.getWhereFieldBySearch(search);
	    	JSONObject searchJson = new JSONObject();
	    	searchJson.put(UserJson.userId, "000");
	    	searchJson.putAll(parmObject.getJson());
	    	
			SqlLang exprotSql  = DBTools2.getExportSql(tableField,selectSB,parmObject.getSearchWhere());
			String parameterArr []  = DBTools2.parsePermeterBySql(exprotSql.getPageSql(),searchJson);
			JSONArray arr = DBTools2.selectArr(exprotSql.getSourceSql(), parameterArr);
			
			OutputStream out = null;
			PageResult.formatType type = PageResult.formatType.valueOf(format);
			String fileName = "";
			switch(type){
				case excel:
					fileName = "Excel-" + System.currentTimeMillis() + ".xls";
					break;
				case csv:
					fileName = "Csv-" + System.currentTimeMillis() + ".csv";
					break;
				case pdf:
					break;
				case word:
					break;
			}
			String headStr = "attachment; filename=\"" + fileName + "\"";
//			responseServlet.setContentType("APPLICATION/OCTET-STREAM");
			responseServlet.setHeader("content-Type", "application/vnd.ms-excel");
			responseServlet.setHeader("Content-Disposition", headStr);
			out = responseServlet.getOutputStream();
			ExportExcel ex = new ExportExcel("用户列表", tableTitles,tableFields, arr);
			ex.export(out);
			out.flush();
			out.close();
			response.put(ResponseJson.status, 1002);
			response.put(ResponseJson.msg, "删除成功");
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_No_Porwer_Query_Field);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Export_Data_Error);
		} catch (Exception e) {
			e.printStackTrace();
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Export_Data_Error);
		}
		return response;
	}
}
